# coding: utf-8

from collections import defaultdict

from flask import render_template, request
from flask_login import login_required

from app.products.brand_forms import BrandSearchForm
from app.products.constant import TypeToName
from app.op.models import User

from . import product_bp
from .models import ProductDesc, ProductTemplate, ProductPrice


@product_bp.route('/supplier/prices', methods=['GET', 'POST'])
@login_required
def price_list():
    """
    供货商产品报价
    :return:
    """
    search_form = BrandSearchForm(formdata=request.form or request.args)
    product_type_id = search_form.product_type_id.data
    prices = ProductDesc.price_statistics(product_type_id)
    template_ids = [each.product_template_id for each in prices]
    templates = ProductTemplate.get_list_by_ids(template_ids)
    template_mapping = {each.id: each for each in templates}

    return render_template(
        'price/price_list.html',
        search_form=search_form,
        prices=prices,
        template_mapping=template_mapping,
        url_kwargs=search_form.data,
        type_name_mapping=TypeToName.mapping
    )


@product_bp.route('/price/<int:template_id>', methods=['GET', 'POST'])
@login_required
def price_detail(template_id):
    """
    供货商产品报价
    :return:
    """

    desc_list = ProductDesc.get_list_by_args(
        product_template_id=template_id
    )
    template = ProductTemplate.get_by_id(template_id)
    product_prices = ProductPrice.get_list_by_args(
        product_template_id=template_id
    )
    user_ids = [each.supplier_id for each in desc_list]
    users = User.get_list_by_ids(user_ids)

    user_mapping = {each.id: each for each in users}

    price_mapping = defaultdict(list)
    for each in product_prices:
        price = '议价' if each.is_consult else each.price
        spec_price = '<p><span>{spec_value}</span>--' \
                     '<span class="text-blue">{price}' \
                     '</span></p>'.format(
            spec_value=each.spec_value,
            price=price
        )
        price_mapping[each.product_desc_id].append(spec_price)

    for each in desc_list:
        each.spec_prices = '<br>'.join(price_mapping[each.id])
        user = user_mapping.get(each.supplier_id)
        if user:
            each.user_name = user.nickname

    return render_template(
        'price/price_detail.html',
        template=template,
        desc_list=desc_list
    )

